package com.wangbl.infomanager;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import com.tangye.android.http.Request.ResponseListener;
import com.wangbl.infomanager.http.Http;
import com.wangbl.infomanager.http.Response;
import com.wangbl.infomanager.utils.Logger;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class UserInfoActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "UserInfoActivity";
	private TextView scan;
	private Button logout;
	private Http http;
	private RelativeLayout layout_push;
	private SharedPreferences config;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_user_info);
		super.onCreate(savedInstanceState);

		sp = getSharedPreferences("push_info", MODE_PRIVATE);
		config = getSharedPreferences("push_msg_state", Context.MODE_PRIVATE);

		logout = (Button) findViewById(R.id.btn_user_info_logout);
		scan = (TextView) findViewById(R.id.user_info_item_2);
		user_info = (TextView) findViewById(R.id.user_info_item_3);
		layout_push = (RelativeLayout) findViewById(R.id.user_info_item_1);
		tv_msg_count = (TextView) findViewById(R.id.user_info_item_1_num);

		// int readCount = config.getInt("readCount", 0);
		// tv_msg_count.setText(readCount+"");
		// if(readCount == 0){
		// tv_msg_count.setText("");
		// }

		title_text.setText("个人信息");
		title_user.setVisibility(View.GONE);
		title_menu.setVisibility(View.GONE);
		title_back.setVisibility(View.VISIBLE);
		
		scan.setOnClickListener(this);
		logout.setOnClickListener(this);
		layout_push.setOnClickListener(this);
		user_info.setOnClickListener(this);
		pd.setCancelable(false);
	}

	@Override
	protected void onResume() {
		super.onResume();
		int readCount = config.getInt("readCount", 0);
		tv_msg_count.setText(readCount + "");
		if (readCount == 0) {
			tv_msg_count.setText("");
		}
	}

	@Override
	protected void interrupt() {
		pd.dismiss();
	}

	private SharedPreferences sp;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.user_info_item_2:
			// Intent intent = new Intent(this,ScanCodeActivity.class);
			// startActivityForResult(intent, 0);
			// 扫码操作
			Intent intent = new Intent(this, CaptureActivity.class);
			startActivityForResult(intent, 0);
			break;
		case R.id.btn_user_info_logout:
			logout();
			Intent i = new Intent(this, MainActivity.class);
			startActivity(i);
			setResult(InfoMainActivity.CLOSE_ACTIVTY);
			finish();

			break;

		case R.id.user_info_item_1:
			if(sp.getAll().size() == 0){
				toast("没有数据...");
				return;
			}
			Intent itn = new Intent(this,PushMsgListActivity.class);
			startActivity(itn);
			break;
			
		case R.id.user_info_item_3:
//			toast("正在建设中...");
			Intent i2 = new Intent(this, UserInfoShowActivity.class);
			startActivity(i2);
			break;
		}

	}

	@SuppressWarnings("deprecation")
	private void logout() {
		CookieSyncManager.createInstance(this);
		CookieSyncManager.getInstance().startSync();
		CookieManager.getInstance().removeAllCookie();
		SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.clear();
		edit.apply();
		JPushInterface.stopPush(getApplicationContext());
	}

	private void codeDoRequest(String url) {
		Logger.i(TAG, "codeDoRequest");
		Logger.i(TAG, "url:" + url);
		if (TextUtils.isEmpty(url)) {
			toast("无效二维码...");
			return;
		}

		if (!url.startsWith("http://")) {
			toast("无效二维码...");
			return;
		}

		pd.show();
		http = new Http(url);
		http.setDebug(Http.isDebug);
		http.asyncRequest(new ResponseListener<Response>() {

			@Override
			public void onResp(int arg0, Response arg1, Object... arg2) {
				pd.dismiss();
				Logger.i(TAG, "json:" + arg1.json);
				toast(parser(arg1.json));
			}

			@Override
			public void onErr(int arg0, String arg1, int arg2, Object... arg3) {
				pd.dismiss();
				toast(arg1);
			}

		});
	}

	// {"state":"3"}

	private String[] values = { "签到失败", "签到成功", "已完成签到", "请勿重复签到", "抱歉，签到时间已过", "抱歉，该活动还未审核", "抱歉，该活动还未申请" };
	private TextView tv_msg_count;
	private TextView user_info;

	private String parser(String json) {
		JSONObject obj;
		try {
			obj = new JSONObject(json);
			int res = obj.getInt("state");
			return values[res];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "无效二维码...";

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Logger.i(TAG, "onActivityResult");
		if (requestCode == 0 && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			String result = bundle.getString("result");
			Logger.i(TAG, "result:" + result);
			codeDoRequest(result);
		}
	}

	/**
	 * 清除WebView缓存
	 */
	// public void clearWebViewCache() {
	//
	// // 清理Webview缓存数据库
	// try {
	// deleteDatabase("webview.db");
	// deleteDatabase("webviewCache.db");
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// Logger.i(TAG, "get:"+getDir("", MODE_PRIVATE));
	// Logger.i(TAG,"getf:"+getFilesDir());
	// File webViewFile = getDir("webview", MODE_PRIVATE);
	// // File f = new File(getDir("",
	// MODE_PRIVATE).getAbsolutePath().replace("app_", ""));
	// // Logger.i(TAG, "f:"+f);
	// // if(f.exists()){
	// // deleteFile(f);
	// // }
	// // File cacheFile = getCacheDir();
	// // Logger.i(TAG, "cache:"+cacheFile);
	// if(webViewFile.exists()){
	// deleteFile(webViewFile);
	// }
	// // if(cacheFile.exists()){
	// // deleteFile(cacheFile);
	// // }
	//
	// }

	/**
	 * 递归删除 文件/文件夹
	 * 
	 * @param file
	 */
	public void deleteFile(File file) {

		Logger.i(TAG, "delete file path=" + file.getAbsolutePath());

		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			Logger.e(TAG, "delete file no exists " + file.getAbsolutePath());
		}
	}

}
